/**
 * @file RoleDistribution.js
 * @description 角色分配相关逻辑
 */

import { ROLES, DISTRIBUTION_CONFIG, GAME_PRESETS, PLUGIN_NAME } from '../config/index.js';

/**
 * 根据玩家人数计算角色分配
 * @param {number} playerCount - 玩家人数
 * @returns {object} 角色分配对象
 */
export function calculateRoleDistribution(playerCount) {
    const config = DISTRIBUTION_CONFIG[playerCount];
    if (!config) {
        throw new Error(`[${PLUGIN_NAME}] 玩家人数 ${playerCount} 不在支持的配置范围内。`);
    }

    let distribution = {
        [ROLES.WEREWOLF]: config.werewolf,
        [ROLES.VILLAGER]: config.villager,
    };

    // 确保预言家被分配
    if (config.god > 0) {
        distribution[ROLES.SEER] = 1;
    }

    const remainingGodCount = config.god - 1;
    let otherGodRoles = [];
    if (playerCount === 6) {
        // 6人局的另一个神是守卫
        otherGodRoles = [ROLES.GUARD];
    } else {
        // 其他人数局的神职（除预言家外）
        otherGodRoles = [ROLES.WITCH, ROLES.HUNTER, ROLES.GUARD, ROLES.IDIOT];
    }

    // 分配剩下的神职
    const otherGodsToAssignCount = Math.min(remainingGodCount, otherGodRoles.length);
    for (let i = 0; i < otherGodsToAssignCount; i++) {
        distribution[otherGodRoles[i]] = 1;
    }

    const actualGodsDistributed = Object.keys(distribution).filter(role =>
        [ROLES.SEER, ROLES.WITCH, ROLES.HUNTER, ROLES.GUARD, ROLES.IDIOT].includes(role) && distribution[role] === 1
    ).length;

    if (config.god > actualGodsDistributed) {
        distribution[ROLES.VILLAGER] += (config.god - actualGodsDistributed);
    }

    return distribution;
}

/**
 * 从预设板子分配角色
 * @param {object} preset - 预设板子对象
 * @returns {object} 角色分配对象
 */
export function assignRolesFromPreset(preset) {
    const distribution = {};
    for (const role in preset.roles) {
        distribution[role] = preset.roles[role];
    }
    return distribution;
}

/**
 * 将计算好的角色分配给玩家
 * @param {Array} players - 玩家列表
 * @param {object} distribution - 角色分配对象
 * @returns {object} 分配结果
 */
export function assignRolesToPlayers(players, distribution) {
    const playerCount = players.length;
    let allRoles = [];
    for (const role in distribution) {
        for (let i = 0; i < distribution[role]; i++) allRoles.push(role);
    }

    if (allRoles.length !== playerCount) {
        return { success: false, message: `角色分配错误：总角色数 ${allRoles.length} 不等于玩家数 ${playerCount}。` };
    }

    allRoles.sort(() => Math.random() - 0.5); // 随机打乱角色顺序
    players.forEach((player, index) => { player.role = allRoles[index]; });
    return { success: true };
}

